<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基本信息 -->
          <a-collapse-panel key="1" header="基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="documentNo">
                  <a-input :disabled="formDisabled1" v-model="model.documentNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlerId">
                  <select-user-by-dep
                    :disabled="formDisabled"
                    :multi="false"
                    v-model="model.handlerId"
                    disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <a-input
                    :disabled="formDisabled1"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm"
                    placeholder="请输入申请时间"
                    disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUser">-->
              <!--                  <select-person-input-->
              <!--                    placeholder="请选择申请人"-->
              <!--                    :disabled="formDisabled"-->
              <!--                    @back="backUserInfo"-->
              <!--                    v-model="model.applyUser"/>-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <!--              <a-col :span="8">-->
              <!--                <a-form-model-item label="申请单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyUnit">-->
              <!--                  <j-select-depart placeholder="请输入申请单位" :disabled="formDisabled" v-model="model.applyUnit"/>-->
              <!--                </a-form-model-item>-->
              <!--              </a-col>-->
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="applyDept">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled1" disabled v-model="model.applyDept"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请车辆" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carId">
                  <div id="carId">
                    <a-tooltip>
                      <template slot="title">
                        查看汽车详情
                      </template>
                      <a @click="getCarInfo()">{{ model.carId_dictText }}</a>
                    </a-tooltip>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="管理员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="carAdmin">
                  <!--                  <select-person-input :disabled="formDisabled"  placeholder="请选择车辆管理员" v-model="model.carAdmin" disabled/>-->
                  <select-user-by-dep :disabled="formDisabled1" placeholder="请选择车辆管理员" :multi="false" v-model="model.carAdmin" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessUnit">
                  <select-team-input
                    :disabled="formDisabled1"
                    v-model="model.businessUnit"
                    :tdlx="3" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="关联项目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                  <select-project-input v-model="model.projectId" placeholder="请输入选择项目" :projectStatus="'2'" :proDisabled="true" :disabled="formDisabled1" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否需要驾驶员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isDriver">
                  <j-dict-select-tag :disabled="formDisabled1" type="list" v-model="model.isDriver" dictCode="YES_OR_NO" placeholder="请选择是否需要驾驶员" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8">
                <a-form-model-item label="用车日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usingStartTime">
                  <j-date :disabled="formDisabled" placeholder="请选择用车日期" v-model="model.usingStartTime" style="width: 100%" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="预计归还日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usingEndTime">
                  <j-date :disabled="formDisabled1" placeholder="请选择预计归还日期" v-model="model.usingEndTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="用车类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="usingType">
                  <j-dict-select-tag :disabled="formDisabled1" type="list" v-model="model.usingType" dictCode="using_type" placeholder="请选择用车类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item v-if="formBpm" label="预定日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reserveStartTime">
                  <a-date-picker
                    :disabled="formDisabled1"
                    placeholder="请选择预定日期始"
                    @change="handleStartChange"
                    :disabled-date="disabledDateStartTime"
                    v-model="model.reserveStartTime"
                    style="width: 47%"
                  />
                  <span class="fontDiy" style="margin-right: 1%;margin-left: 1%;">至</span>
                  <a-date-picker
                    :disabled="formDisabled1"
                    :disabled-date="disabledDate"
                    :default-picker-value="model.insuranceStartTime"
                    placeholder="请选择预定日期止"
                    v-model="model.reserveEndTime"
                    @change="handleEndChange"
                    style="width: 47%"
                  />
                </a-form-model-item>
                <a-form-model-item v-else label="预定日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reserveStartTime">
                  <a-date-picker
                    :disabled="formDisabled1"
                    placeholder="请选择预定日期始"
                    @change="handleStartChange"
                    :disabled-date="disabledDateStartTime"
                    v-model="model.reserveStartTime"
                    style="width: 47%"
                  />
                  <span class="fontDiy" style="margin-right: 1%;margin-left: 1%;">至</span>
                  <a-date-picker
                    :disabled="formDisabled1"
                    :disabled-date="disabledDate"
                    :default-picker-value="model.insuranceStartTime"
                    placeholder="请选择预定日期止"
                    v-model="model.reserveEndTime"
                    @change="handleEndChange"
                    style="width: 47%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.isDriver == '1' && formDisabled1">
                <a-form-model-item label="驾驶员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="driver">
                  <!--                  <select-person-input v-model="model.driver" placeholder="请输入驾驶员" disabled />-->
                  <select-user-by-dep :disabled="formDisabled" placeholder="请输入驾驶员" :multi="false" v-model="model.driver"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否已还车" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isReturnCar" v-if="formDisabled1">
                  <j-dict-select-tag type="list" v-model="model.isReturnCar" dictCode="YES_OR_NO" placeholder="请选择是否已还车" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="还车日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="returnCarTime" v-if="formDisabled1">
                  <j-date placeholder="请选择还车日期" v-model="model.returnCarTime" style="width: 100%" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="事由" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="subjectMatter">
                  <a-textarea :disabled="formDisabled1" :max-length="500" v-model="model.subjectMatter" rows="4" placeholder="请输入事由"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled1" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="2" header="附件信息">
            <a-row>
              <a-col :span="24">
                <a-form-model-item label="附件信息" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="fileInfo">
                  <j-upload :disabled="formDisabled1" v-model="model.fileInfo" ></j-upload>
                </a-form-model-item>
              </a-col>
              <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col> -->
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <erp-car-info-modal ref="modalForm"></erp-car-info-modal>

    <ErpCarUsingSelectDriverFormPrint
      v-if="formBpm && isSubmit"
      id="carusingselectContent"
      class="print_style"
      :formData="model1"
      :formDisabled="formDisabled1"
      :formBpm="formBpm"
      :formDataHistory="formData"></ErpCarUsingSelectDriverFormPrint>
  </a-spin>
</template>
<style>
@import "../../../../utils/print.css";
#carId {
  width: 100%;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  color: rgba(0, 0, 0, 0.65);
  background-color: #fafafa;
  opacity: 1;
  margin-top: 3px;
  padding-left: 10px;
  line-height: 34px;
}
</style>
<script>

import { getAction, httpAction } from '@/api/manage'
import moment from 'moment';
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
import { mapGetters } from 'vuex';
import ErpCarInfoModal from '@/views/oa/car/modules/ErpCarInfoModal'
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import CommonFlowList from '@/views/components/CommonFlowList.vue';
import Print from '@/utils/print/printarea.js';
import ErpCarUsingSelectDriverFormPrint from './ErpCarUsingSelectDriverFormPrint'; // 打印
export default {
    name: 'ErpCarUsingSelectDriverForm',
    components: {
      JSelectDepart,
      SelectUserByDep,
      SelectTeamInput,
      SelectProjectInput,
      ErpCarInfoModal,
      CommonFlowList,
      ErpCarUsingSelectDriverFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        isSubmit: true,
        reserveStartDate: '', // 预定开始日期
        reserveEndDate: '', // 预定结束日期
        add_edit: '',
        activeKey: ['1', '2'],
        model: {
          checkStatus: 0
        },
        model1: { // 打印
          checkStatus: 0
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
        // applyUser: [
        //     { required: true, message: '请选择申请人!', trigger: 'change'}
        // ],
        // applyUnit: [
        //     { required: true, message: '请选择申请单位!', trigger: 'change'}
        // ],
        applyDept: [
          { required: true, message: '请选择申请部门!', trigger: 'change' }
        ],
        usingType: [
            { required: true, message: '请选择用车类型!', trigger: 'blur' }
        ],
        carId: [
          { required: true, message: '请选择申请车辆!', trigger: 'blur' }
        ],
        reserveStartTime: [
          { required: true, message: '请选择预定日期!', trigger: 'change' }
        ],
        businessUnit: [
          { required: true, message: '请选择业务团队!', trigger: 'change' }
        ],
        // 2022年10月17日18:33:55 关联项目改为非必填
        // projectId: [
        //   { required: true, message: '请选择关联项目!', trigger: 'change'}
        // ],
        isDriver: [
          { required: true, message: '请选择是否需要驾驶员!', trigger: 'blur' }
        ],
        usingStartTime: [
          { required: true, message: '请选择用车日期!', trigger: 'change' }
        ],
        usingEndTime: [
          { required: true, message: '请选择预计归还日期!', trigger: 'change' }
        ],
        subjectMatter: [
          { required: true, message: '请输入事由!', trigger: 'blur' }
        ]
        },
        url: {
          add: '/api/erp/erpcarusing/erpCarUsing/add',
          edit: '/api/erp/erpcarusing/erpCarUsing/edit',
          queryById: '/api/erp/erpcarusing/erpCarUsing/queryById',
          queryByCarId: '/api/erp/oa/car/erpCarInfo/queryById',
          generatedFormNumber: '/api/erp/base/generatedFormNumber'
        },
        carInfo: {}
      }
    },
    computed: {
      formDisabled1() {
        return true
      },
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowDataById();
    },
    methods: {
      generatedFormNumber() {
        getAction(this.url.generatedFormNumber, { prefix: 'YC', subSystemCode: '04' }).then(res => {
          if (res.success) {
            this.$set(this.model, 'documentNo', res.result)
          }
        })
      },
      moment,
      handleStartChange(value, date) {
        this.reserveStartDate = date
        if (this.model.reserveEndTime) {
          if (moment(this.model.reserveEndTime).diff(moment(this.model.reserveStartTime), 'days') < 0) {
            this.model.reserveEndTime = this.model.reserveStartTime
          }
        }
      },
      handleEndChange (value, date) {
        this.reserveEndDate = date
      },
      disabledDate(current) {
        return current < moment(this.model.reserveStartTime).subtract('day')
      },
      disabledDateStartTime(current) {
        return current && current < moment().subtract(1, 'days'); // 当天之前的不可选，不包括当天
      },
      // 关联项目
      selectProject(data) {
        if (data) {
            this.$set(this.model, 'projectId', '');
            this.$set(this.model, 'projectUndertaker', '')
            this.$set(this.model, 'teamId', '')
        }
      },
      ...mapGetters(['userInfo']),
      add (record) {
        this.$refs.form.resetFields();
        if (record) {
          this.model = Object.assign({}, this.modelDefault);
        }
        this.$set(this.model, 'createBy', this.userInfo().empId) // 申请人
        this.model.applyDept = this.userInfo().deptId
        this.$set(this.model, 'carAdmin', record.carAdmin) // 管理员名称
        this.$set(this.model, 'carAdmin_dictText', record.carAdmin_dictText) // 管理员名称
        if (record.startStr) {
          this.$set(this.model, 'reserveStartTime', record.startStr)
          this.$set(this.model, 'reserveEndTime', record.endStr)
          this.reserveStartDate = record.startStr
          this.reserveEndDate = record.endStr
        }
        if (record.id) {
          this.$set(this.model, 'carId', record.id)
        }
        getAction(this.url.queryByCarId + '?id=' + this.model.carId, {}).then((res) => {
          if (res.success) {
            this.carInfo = res.result;
          }
        });
        if (record.carName) {
          this.$set(this.model, 'carId_dictText', record.carName)
        }
        this.$set(this.model, 'createTime', moment().format('YYYY-MM-DD HH:mm'))
        this.formDisabled = false
        this.add_edit = 'add'
        this.generatedFormNumber();
      },
      async edit (record) {
        this.$refs['form'].clearValidate();
        this.model = Object.assign({}, record);
        this.model1 = Object.assign({}, record);
        await getAction(this.url.queryByCarId + '?id=' + this.model.carId, {}).then((res) => {
          if (res.success) {
            this.carInfo = res.result;
            this.$set(this.model, 'carId_dictText', this.carInfo.carNum)
            this.$set(this.model1, 'carId_dictText', this.carInfo.carNum)
          }
        });
        // yyyy-MM-dd HH:mm:ss
        this.reserveStartDate = record.reserveStartTime
        this.reserveEndDate = record.reserveEndTime
        this.visible = true;
        this.add_edit = 'edit'
      },
      // 渲染流程表单数据
      showFlowDataById() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm () {
        const that = this;
        this.isSubmit = false
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (this.add_edit == 'add') {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
               method = 'put';
            }
            if (this.reserveEndDate.indexOf('23:59:59') != -1) {
              this.model.reserveEndTime = this.reserveEndDate
            } else {
              this.model.reserveEndTime = this.reserveEndDate + ' ' + '23:59:59'
            }
            if (this.reserveStartDate.indexOf('00:00:00') != -1) {
              this.model.reserveStartTime = this.reserveStartDate
            } else {
              this.model.reserveStartTime = this.reserveStartDate + ' ' + '00:00:00'
            }
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');

                if (this.formBpm === true) {
                  if (!this.formData.dataId) return false
                  let params = { id: this.formData.dataId };
                  getAction(this.url.queryById, params).then((res) => {
                    if (res.success) {
                      this.model1 = res.result
                      this.isSubmit = true
                    }
                  });
                }
              } else {
                that.$message.warning(res.message);
                that.$emit('unButtonDisable');
              }
            }).catch((error) => {
              that.$emit('unButtonDisable');
            }).finally(() => {
              that.confirmLoading = false;
            })
          } else {
            that.$emit('unButtonDisable');
          }
        })
      },
      getCarInfo() {
        this.$refs.modalForm.edit(this.carInfo);
        this.$refs.modalForm.title = '详情';
        this.$refs.modalForm.disableSubmit = true;
      },
      backUserInfo(data) {
        this.model.applyUnit = data[0].orgDepart;// 申请人单位
        this.model.applyDept = data[0].departmentId;// 申请人部门
      },

        // 点击打印
      onPrint () {
        let print = new Print({
          el: '#carusingselectContent',
          popTitle: '车辆使用申请详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
